﻿using System;
using System.Text;
using PengSW.TcpService;
using static PengSW.RuntimeLog.RL;

namespace ProtocolAnalyzer
{
    public class AnalyzeProtocol : Protocol
    {
        public AnalyzeProtocol(ProtocolRule aProtocolRule)
        {
            ReceiveTimeOut = aProtocolRule.ReceiveTimeOut;
            Rule = aProtocolRule;
        }

        public ProtocolRule Rule { get; set; }
        public Encoding[] Encodings => AnalyzeModel.Encodings;
        
        protected override bool AnalyBytes(byte[] aBytes)
        {
            string aTextFrame = Rule.Encoding.GetString(aBytes);
            ClarifyFrameReceived(aTextFrame);

            if (Rule == null) return false;
            string aResponseText = Rule.GetResponse(aTextFrame);
            if (aResponseText != null) SendText(aResponseText);
            return true;
        }

        protected override bool HasFrameHead(byte[] aBytes)
        {
            return true;
        }

        protected override bool HasFrameTail(byte[] aBytes)
        {
            return true;
        }

        protected override void OnStart()
        {
            if (Rule == null) return;
            if (Rule.SendAfterConnected == null) return;
            SendText(Rule.SendAfterConnected);
        }

        public void SendText(string aText)
        {
            L($"向[{_Connection}以编码[{Rule.Encoding.EncodingName}]发送[{aText}]……");
            if (Rule.AppendNewLine) aText += Environment.NewLine;
            _Connection.SendText(aText, Rule.Encoding);
        }
    }
}
